package com.goldcn.sys.service;

import com.goldcn.Interceptor.CurrentUser;
import com.goldcn.common.BaseCode;
import com.goldcn.common.CommonUtils;
import com.goldcn.common.ResultData;
import com.goldcn.config.PropertiesConfig;
import com.goldcn.sys.dao.GcnSysRoleMapper;
import com.goldcn.sys.dao.GcnSysUserInfoMapper;
import com.goldcn.sys.dao.GcnSysUserMapper;
import com.goldcn.sys.dao.GcnSysUserRoleMapper;
import com.goldcn.sys.model.GcnSysUser;
import com.goldcn.sys.model.GcnSysUserInfo;
import com.goldcn.sys.model.GcnSysUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/6.
 */
@Service
@Transactional
public class UserManageService {
    @Autowired
    GcnSysUserMapper gcnSysUserMapper;
    @Autowired
    GcnSysRoleMapper gcnSysRoleMapper;
    @Autowired
    GcnSysUserInfoMapper gcnSysUserInfoMapper;
    @Autowired
    GcnSysUserRoleMapper gcnSysUserRoleMapper;
    @Autowired
    PropertiesConfig config;

    public ResultData<Object> getUser(String userId) {
        ResultData<Object> resultData = new ResultData<Object>();
        List<Map<String,Object>> userRoleList;
        Map<String,Object> userInfoMap;
        userRoleList = gcnSysUserRoleMapper.getUserRole(userId);
        StringBuffer rolesStr = new StringBuffer();
        for(int i=0;i<userRoleList.size();i++){
            if(i==0){
                rolesStr.append(userRoleList.get(i).get("roleID"));
            }else {
                rolesStr.append(","+userRoleList.get(i).get("roleID"));
            }
        }
        userInfoMap=gcnSysUserMapper.getUserInfo(userId);
        userInfoMap.put("roleID",rolesStr);
        resultData.setData(userInfoMap);
        return resultData;

    }

    public ResultData addUser(Map<String, String> map, HttpServletRequest request) throws Exception {
        CurrentUser currentUser = (CurrentUser)request.getAttribute("user");
        String userId = CommonUtils.getGUID();
        ResultData result = new ResultData<Object>();
        int IsExistName = validUnique(map.get("userName"),userId);
        String passWord = map.get("passWord");
        if(CommonUtils.isEmpty(passWord))
            passWord = config.getEmployeeInitPwd();
        passWord = CommonUtils.MD5(CommonUtils.hash(passWord));
        if(IsExistName == 1){
            result.setCode("ExistName");
        }else{
            //sysUser对象
            GcnSysUser sysUser = new GcnSysUser();
            sysUser.setIsAdmin(1);//非管理员
            sysUser.setAddTime(System.currentTimeMillis());
            sysUser.setChinaName(map.get("chinaName"));
            sysUser.setIsStop(0);
            sysUser.setUserID(userId);
            sysUser.setPassWord(passWord);
            sysUser.setUserName(map.get("userName"));
            //SysUserInfo对象
            GcnSysUserInfo userInfo = new GcnSysUserInfo();
            userInfo.setInfoID(CommonUtils.getGUID());
            userInfo.setUserID(userId);
            userInfo.setMobile(map.get("mobile"));
            userInfo.setEmail(map.get("email"));
            userInfo.setQQ(map.get("QQ"));

            sysUser.setAddTime(System.currentTimeMillis());
            sysUser.setAddUser(currentUser.getUserID());
            gcnSysUserMapper.insertSelective(sysUser);
            userInfo.setAddTime(System.currentTimeMillis());
            userInfo.setAddUser(currentUser.getUserID());
            gcnSysUserInfoMapper.insertSelective(userInfo);
            if(CommonUtils.isNotEmpty(map.get("roleID"))){
                //SysUserRole对象
                GcnSysUserRole SysUserRole = new GcnSysUserRole();
                SysUserRole.setUserID(userId);
                SysUserRole.setAddTime(System.currentTimeMillis());
                SysUserRole.setIsStop(0);
                String[] rolesID = map.get("roleID").split(",");
                for (int i = 0; i < rolesID.length; i++) {
                    SysUserRole.setID(CommonUtils.getGUID());
                    SysUserRole.setRoleID(rolesID[i]);
                    gcnSysUserRoleMapper.insertSelective(SysUserRole);
                }
            }
        }
        return result;
    }

    public ResultData updateUser(Map<String, String> map, HttpServletRequest request) {
        CurrentUser currentUser = (CurrentUser)request.getAttribute("user");
        ResultData result = new ResultData();
        int IsExistName = validUnique(map.get("userName"),map.get("userId"));
        if(IsExistName == 1){
            result.setCode("ExistName");
        }else{
            //sysUser对象
            GcnSysUser sysUser = gcnSysUserMapper.selectByPrimaryKey(map.get("userId"));
            String passWord = map.get("passWord")==""?null:map.get("passWord");
            if(CommonUtils.isNotEmpty(passWord)){
                passWord = CommonUtils.MD5(CommonUtils.hash(passWord));
            }
            if(CommonUtils.isNotEmpty(passWord) && !sysUser.getPassWord().equals(passWord))
                sysUser.setIsInitPsw(0);
            sysUser.setPassWord(passWord);
            sysUser.setAddTime(System.currentTimeMillis());
            sysUser.setChinaName(map.get("chinaName"));
            sysUser.setUserName(map.get("userName"));
            sysUser.setUpdateUser(currentUser.getUserID());
            sysUser.setUpdateTime(System.currentTimeMillis());
            gcnSysUserMapper.updateByPrimaryKeySelective(sysUser);
            GcnSysUserInfo userInfo1 = gcnSysUserInfoMapper.selectInfoByUserID(map.get("userId"));
            if(userInfo1!=null) {
                //SysUserInfo对象
                userInfo1.setMobile(map.get("mobile"));
                userInfo1.setEmail(map.get("email"));
                userInfo1.setQQ(map.get("QQ"));
                userInfo1.setUpdateUser(currentUser.getUserID());
                userInfo1.setUpdateTime(System.currentTimeMillis());
                gcnSysUserInfoMapper.updateByPrimaryKeySelective(userInfo1);
            }else{
                GcnSysUserInfo userInfo = new GcnSysUserInfo();
                userInfo.setInfoID(CommonUtils.getGUID());
                userInfo.setUserID(map.get("userId"));
                userInfo.setMobile(map.get("mobile"));
                userInfo.setEmail(map.get("email"));
                userInfo.setQQ(map.get("QQ"));
                userInfo.setAddUser(currentUser.getUserID());
                userInfo.setAddTime(System.currentTimeMillis());
                gcnSysUserInfoMapper.insertSelective(userInfo);
            }
            gcnSysUserRoleMapper.deleteByUserID(map.get("userId"));
            if(CommonUtils.isNotEmpty(map.get("roleID"))){
                String[] rolesID = map.get("roleID").split(",");
                //SysUserRole对象
                GcnSysUserRole sysUserRole = new  GcnSysUserRole();
                sysUserRole.setUserID(map.get("userId"));
                sysUserRole.setAddTime(System.currentTimeMillis());
                sysUserRole.setIsStop(0);
                for (int i = 0; i < rolesID.length; i++) {
                    sysUserRole.setID(CommonUtils.getGUID());
                    sysUserRole.setRoleID(rolesID[i]);
                    gcnSysUserRoleMapper.insertSelective(sysUserRole);
                }
            }
        }
        return result;
    }

    public Map selectAll(Map<String,String> params) {
        //条件
        String CNName = params.get("CNName");
        String USName = params.get("USName");
        String state = params.get("isStop");
        int isStop = 100;
        if(state!=""&&state!=null){
            isStop = Integer.parseInt(state);
        }
        //分页
        int pageSize = Integer.parseInt(params.get("pageSize"));
        int pageIndex = Integer.parseInt(params.get("pageIndex"))*pageSize;
        String sortField = params.get("sortField");
        String sortOrder = params.get("sortOrder");
        String condition = "";
        if(CommonUtils.isNotEmpty(CNName)){
            condition = "and us.chinaName like '%"+CNName+"%'";
        }
        if(CommonUtils.isNotEmpty(USName)){
            condition += " and us.userName like '%"+USName+"%'";
        }
        if(isStop==0||isStop==1){
            condition += " and us.isStop= "+isStop;
        }
        int pageCount = gcnSysUserMapper.selectAllNum(condition);
        List<Object> userList = gcnSysUserMapper.selectAll(pageIndex,pageSize,condition,sortField,sortOrder);
        HashMap result = new HashMap();
        result.put("data", userList);
        result.put("total", pageCount);
        return result;
    }

    public ResultData<Object> stopOrUse(String userId, String stop) {
        ResultData<Object> result = new ResultData<Object>();
        GcnSysUser sysUser = gcnSysUserMapper.selectByPrimaryKey(userId);
        if(sysUser.getIsAdmin()==0){
            result.setCode("0");
            return result;
        }
        if(stop.equals("0")){
            sysUser.setIsStop(1);
        }else{
            sysUser.setIsStop(0);
        }
        gcnSysUserMapper.updateByPrimaryKeySelective(sysUser);
        result.setCode(BaseCode.SUCCESS_CODE);
        return result;
    }

    public ResultData<Object> deleteUser(String userId) {
        ResultData result = new ResultData();
        GcnSysUser sysUser = gcnSysUserMapper.selectByPrimaryKey(userId);
        if(sysUser.getIsAdmin()==0){
            result.setCode("0");
            return result;
        }
        gcnSysUserInfoMapper.deleteByUserID(userId);
        gcnSysUserRoleMapper.deleteByUserID(userId);
        gcnSysUserMapper.deleteByPrimaryKey(userId);
        result.setCode(BaseCode.SUCCESS_CODE);
        return result;
    }

    public int validUnique(String userName, String userID) {
        String condition = "";
        int result;
        if(CommonUtils.isNotEmpty(userName)){
            condition += " and  u1.userName= binary'"+userName+"'";
        }
        if(CommonUtils.isNotEmpty(userID)){
            condition += " and u1.userID not in (  " +
                    "  select u2.userID from gcn_sys_user u2  " +
                    "  where u2.userID= '"+userID+"'" +
                    " and u2.userName=binary'"+userName+"')";
        }
        int record = gcnSysUserMapper.validUnique(condition);
        if(record > 0){
            //存在相同列数据
            result = 1;
        }else{
            //不存在相同列数据
            result = 0;
        }
        return result;
    }

    public ResultData<Map<String,Object>> currUserInfo(HttpServletRequest request) {
        ResultData<Map<String,Object>> result = new ResultData<Map<String,Object>>();
        Map<String,Object> map = new HashMap<String,Object>();
        CurrentUser user =  (CurrentUser)request.getAttribute("user");
        map.put("chinaName",gcnSysUserMapper.selectByPrimaryKey(user.getUserID()).getChinaName());
        result.setData(map);
        return result;
    }
}
